package nsn.message.aggregator.views.sources;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import nsn.message.aggregator.model.IMessageAggregator;

import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.part.ViewPart;

/**
 * 
 * @author Lukasz Nowak
 * @since 13-03-2011
 * 
 */
public class SourcesView extends ViewPart {

	private TreeViewer _treeViewer;
	
	private PropertyChangeListener _modelChangeListener;

	/**
	 *
	 */
	public SourcesView() {
		super();
	}

	@Override
	public void createPartControl(final Composite parent) {
		// Create tree viewer
		_treeViewer = new TreeViewer(parent, //
				SWT.SINGLE | SWT.V_SCROLL);
		_treeViewer.setContentProvider(//
				new BaseWorkbenchContentProvider());
		_treeViewer.setLabelProvider(//
				new WorkbenchLabelProvider());
		

		// Obtain input and register model listener
		final IMessageAggregator model = getInput();		
		model.addPropertyChangeListener(getModelChangeListener());
		_treeViewer.setInput(model);

		// create a menu Manager
		final MenuManager menuManager = new MenuManager();
		final Menu menu = menuManager.createContextMenu(_treeViewer.getTree());
		// Set the MenuManager
		_treeViewer.getTree().setMenu(menu);
		getSite().registerContextMenu(menuManager, _treeViewer);
		
		//Set selection
		getSite().setSelectionProvider(_treeViewer);

	}


	@Override
	public void setFocus() {
		_treeViewer.getControl().setFocus();
	}

	@Override
	public void dispose() {
		getInput().removePropertyChangeListener(getModelChangeListener());
		_treeViewer = null;
		super.dispose();
	}


	/**
	 *
	 * @return
	 */
	private PropertyChangeListener getModelChangeListener() {
		if(_modelChangeListener == null){
			_modelChangeListener = new PropertyChangeListener() {
				
				@Override
				public void propertyChange(final PropertyChangeEvent event) {
					Display.getDefault().syncExec(new Runnable() {
						
						@Override
						public void run() {
							_treeViewer.refresh();							
						}
					});
					
				}
			};
			
		}return _modelChangeListener;
	}

	private IMessageAggregator getInput() {
		final Object obj = getSite().getService(IMessageAggregator.class);
		if(obj instanceof IMessageAggregator){
			return (IMessageAggregator)obj;
			
		}
		return null;
	}

}
